<template>
  <div class="is-vertical" :style="{
    display: 'flex',
    flex: 1,
    flexBasis: 'auto',
    flexDirection: 'column',
  }">
    <Matchheader v-bind="{
      time, submit, title: match ? match.name : '',
      save, saveloading,
      timeshow: true,
      isMatch
    }">
    </Matchheader>
    <Question ref="ques" v-if="question && question.type === '代码'" v-bind="{
      question,
      questionlist: list,
      index: Number(index),
      setuserdata,
      userdata,
      match,
    }">
      <Matchfooter v-bind="{
        index: Number(index),
        questionlist: list,
        routername: '测评答题',
        userquestion: matchuser?.userquestion || [],
      }"></Matchfooter>
    </Question>
    <questionselect ref="select" v-if="question && question.type !== '代码'" v-bind="{
      question,
      questionlist: list,
      index: Number(index),
      setuserdata,
      userdata,
    }">
      <Matchfooter v-bind="{
        index: Number(index),
        questionlist: list,
        routername: '测评答题',
        userquestion: matchuser?.userquestion || [],
      }"></Matchfooter>
    </questionselect>
  </div>
</template>

<script setup lang="ts">

import { ElMessage, ElMessageBox } from "element-plus";
import { Socket } from "socket.io-client";
import { assign } from "underscore";
import {
  computed,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  Apimatchuserquestion,
  asyncgetquestion,
  asyncgettmpmatchuserdata,
  asyncsavetmpmatchuserdata,
  jilurizhi,
} from "../../../api";
import { Storekey } from "../../../interface";
import { TTestquestion } from "../../../mysql_interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { dealy } from "../../../util/time";
import Matchfooter from "../match/matchfooter.vue";
import Matchheader from "../match/matchheader.vue";
import Question from "../match/question.vue";
import questionselect from "../match/questionselect.vue";

const testquestion: TTestquestion = "testquestion";
const p = defineProps<{
  index: string,
  match: Studycodemodel.Iquestionbank,
  time: { isok: boolean; d: number; h: number; m: number; s: number },
  matchuser: Apimatchuserquestion[],
  start: () => void,
  isnot: { err: number; msg: string },
  setresult?: Function, sub?: boolean, testid: string
}>()

const isMatch = false

interface TestQ extends Studycodemodel.Iquestion {
  example?: Studycodemodel.Iquestion["testcases"];
}

const { index } = toRefs(p);
const list = computed<Studycodemodel.Iquestion[]>(() => {
  return (
    p.match?.questionquestionbank?.map((v) => {
      return v.question || {};
    }) || []
  );
});
const store = useStore(Storekey);

const router = useRouter();
const user = computed<Studycodemodel.Iuser>(() => {
  return store.getters.getuser;
});

const ques = ref<typeof Question>();
const select = ref<typeof questionselect>();

const userdata = reactive<Record<string, any>>({});
const question = ref<TestQ>({});
function setuserdata(key: string, context: any) {
  userdata[key] = context;
}

const saveloading = ref(false)
watch(userdata, async () => {
  if (!p.match.ID) {
    return;
  }
  saveloading.value = true
  await dealy();
  await asyncsavetmpmatchuserdata({
    activityid: p.match.ID + "_" + p.testid,
    data: userdata,
    seconds: 1000 * 60 * 60 * 24 * 7,
  });
  saveloading.value = false
});

watch(
  () => list.value,
  async () => {
    await start();
  }
);

watch(
  () => index.value,
  async () => {
    await start();

    if (Number(p.index) > list.value.length) {
      router.push({
        name: "测试答题",
        params: {
          index: 0,
        },
      });
    }
  }
);

function save() {
  if (!p.match.ID) {
    return;
  }

  if (ques.value?.context) {
    if (ques.value.context && question.value?.ID) {
      userdata[question.value.ID] = assign({}, userdata[question.value.ID], {
        context: ques.value.context,
        language: ques.value.language || "CPP",
        gccoptimize: ques.value.gccoptimize ? '-O2' : undefined,
      })
    }
  }
}

function submit() {
  if (!p.match.ID) {
    return;
  }
  if (ques.value) {
    if (ques.value.context && question.value.ID) {
      userdata[question.value.ID] = {
        context: ques.value.context,
        language: ques.value.language || "CPP",
        gccoptimize: ques.value.gccoptimize ? '-O2' : undefined,
      };
    }
  }
  const t = list.value.map((v) => {
    const obj: Studycodemodel.Imatchuserquestion = {};
    if (v.ID) {
      const context = userdata[v.ID];

      obj.type = v.type;
      obj.questionid = v.ID;
      obj.info = {};
      if (v.type !== "代码") {
        obj.questionid;
        obj.info.answer = context;
      } else {
        obj.context = context?.context;
        obj.language = context?.language;
        obj.gccoptimize = context?.gccoptimize ? '-O2' : undefined;
      }
      return obj;
    }
    return {};
  });
  // 如果强制提交
  const socket: Socket =
    store.state.socket;

  ElMessageBox.confirm("是否已经完成要提交", "提交")
    .then(() => {
      if (!p.match.ID) {
        return;
      }
      socket.emit(testquestion, {
        questionbankid: p.match.ID,
        data: t,
        userid: user.value.ID,
        testid: p.testid,
      });
      const arr: [string, any][] = [];

      arr[0] = ["_method_", "test"];
      arr[1] = ["type", "scoket"];
      arr[2] = ["ismatch", false];
      arr[3] = ["matchid", p.match.ID];
      arr[4] = ["matchname", p.match.name];
      jilurizhi(arr);
      router.push({ name: "测评结束", query: { testid: p.testid } });
    })
    .catch((e: any) => {
      ElMessage.error(e);
    });
}

async function Mounted() {
  await p.start();
  if (!user.value) {
    ElMessage.error("请登录");
    router.push("/");
  }
  if (!p.match?.ID) {
    router.push("/");
    return;
  }
  if (list.value.length === 0) {
    ElMessage.error("此次测评未配置题目");
    router.push("/");
  }
  asyncgettmpmatchuserdata({
    activityid: p.match.ID + "_" + p.testid,
  })
    .then((olddata = {}) => {
      Object.assign(userdata, olddata);
      // 缓存数据获取
      let id;
      if (question.value?.ID) {
        const data = (olddata as any)[question.value.ID];
        if (data) {
          id = data;
        }
      }
      if (ques.value) {
        if (!ques.value.context) {
          ques.value.context = id?.context;
          ques.value.language = id?.language || "CPP";
        }
      }
      if (select.value) {
        if (!select.value.data) {
          select.value.data = id;
        }
      }
    })
    .catch((e) => {
      console.log(e);
    });
}
async function start() {
  const data = list.value[Number(index.value)];
  if (data && data.ID) {
    question.value = await asyncgetquestion({
      ID: data.ID,
    });
    question.value.example = question.value.testcases;
  }
}

onMounted(async () => {
  await start();
  Mounted();
});

</script>


<style scoped></style>